package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/samaa/photosalesplus/backend/internal/services"
	"github.com/samaa/photosalesplus/backend/internal/storage"
)

type UploadHandler struct {
	service services.UploadService
}

func NewUploadHandler(service services.UploadService) *UploadHandler {
	return &UploadHandler{service: service}
}

func (h *UploadHandler) UploadImage(c *gin.Context) {
	h.handleUpload(c, services.UploadOptions{})
}

func (h *UploadHandler) UploadAvatar(c *gin.Context) {
	opts := services.UploadOptions{
		MaxBytes:     3 * 1024 * 1024,
		AllowedMIMEs: []string{"image/jpeg", "image/png", "image/gif"},
	}
	h.handleUpload(c, opts)
}

func (h *UploadHandler) handleUpload(c *gin.Context, opts services.UploadOptions) {
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, APIResponse{Error: "请提供文件"})
		return
	}

	asset, err := h.service.SaveImage(c.Request.Context(), file, header, opts)
	if err != nil {
		respondError(c, http.StatusInternalServerError, err)
		return
	}

	respondSuccess(c, gin.H{
		"url":          storage.BuildURL(asset.PreviewPath),
		"preview_url":  storage.BuildURL(asset.PreviewPath),
		"thumb_url":    storage.BuildURL(asset.ThumbPath),
		"original_url": storage.BuildURL(asset.OriginalPath),
		"asset":        asset,
	}, nil)
}
